package neu.competition.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import neu.competition.dto.CompetitionsDTO;
import neu.competition.dto.TeamDTO;
import neu.competition.dto.UserDTO;
import neu.competition.entity.MembershipType;
import neu.competition.entity.Team;
import neu.competition.entity.User;
import neu.competition.mapper.MembershipTypeMapper;
import neu.competition.mapper.TeamMapper;
import neu.competition.mapper.UserMapper;
import neu.competition.service.CompetitionsService;
import neu.competition.service.TeamService;
import neu.competition.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 商城视图
 *
 * @author lemonit.cn-liuri
 */
@Controller
public class HomeController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CompetitionsService competitionsService;
    @Autowired
    UserServiceImpl userService;
    /**
     * 商城首页视图
     *
     * @return 商城首页视图
     */
    @Autowired
    TeamMapper teamMapper;
    @Autowired
    MembershipTypeMapper membershipTypeMapper;
    @Autowired
    TeamService ts;
    @Autowired
    private HttpSession session;

    @GetMapping("/manageTeam")
    public String manageTeam(Model model, HttpSession session) {
        UserDTO user = (UserDTO) session.getAttribute("USER_INFO");

        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("captainId", user.getUserid());
        List<Team> list = teamMapper.selectList(queryWrapper);
        model.addAttribute("myTeams", list);

        return "team/manageTeam";
    }

    @GetMapping("/createTeam")
    public String createTeam(Model model) {


        return "team/create-team";
    }

    @PostMapping("/toCreateTeam")
    public String toCreateTeam(Model model, String teamname, String teamLogo,
                               @RequestParam("teachers[]") List<String> teachers, @RequestParam("students[]") List<String> students) {
        Team team = new Team();
        UserDTO user = (UserDTO) session.getAttribute("USER_INFO");
        team.setTeamLogo("静态");
        team.setCaptainid(user.getUserid());
        team.setTeamname(teamname);
        team.setAdviserTeacher(teachers.get(0));
        System.out.println(team);

        team.setTeamid(getTeamMax() + 1);
        teamMapper.insert(team);

        boolean res = judgeNum(students);
        if (res) {
            MembershipType membershipType = new MembershipType();
            membershipType.setTeamid(team.getTeamid());
            membershipType.setUserid(user.getUserid());
            membershipTypeMapper.insert(membershipType);
            for (int i = 0; i < students.size(); i++) {
                membershipType = new MembershipType();

                membershipType.setTeamid(team.getTeamid());
                membershipType.setUserid(students.get(i));
                membershipTypeMapper.insert(membershipType);
            }
            return "redirect:/manageTeam";
        } else {
            return "Error.html";
        }
    }

    boolean judgeNum(List<String> students) {

        int ans = 0;
        List<User> arrayList = new ArrayList<>();
        arrayList = userMapper.selectList(null);
        int num = students.size();
        for (int i = 0; i < students.size(); i++) {
            String userId = students.get(i);
            for (int j = 0; j < arrayList.size(); j++) {
                if (arrayList.get(j).getUserid().equals(userId)) {
                    ans++;
                }
            }
        }
        return ans == num;
    }

    int getTeamMax() {
        List<Team> teamList = new ArrayList<>();
        teamList = teamMapper.selectList(null);
        int maxn = -1;
        for (int i = 0; i < teamList.size(); i++) {
            if (maxn < teamList.get(i).getTeamid())
                maxn = teamList.get(i).getTeamid();
        }
        return maxn;
    }

    @GetMapping("/")
    public String mallIndex(Model model, HttpSession session) {
/*        List<Shop> newShopList = shopService.searchShop(0, "").getList().subList(0, 5);
        model.addAttribute("shopList", newShopList);
        List<GoodsDTO> newGoodsList = goodsService.listLatestGoods(10);
        model.addAttribute("goodsList", newGoodsList);*/
        List<CompetitionsDTO> list = competitionsService.getAllCompetitionsDTOListThree();
        model.addAttribute("competitionsDTOS", list);
        if(session.getAttribute("USER_INFO")!=null)
            return "competition/competition-login";
        return "competition/index";
    }

    @GetMapping("/index")
    public String goIndex(Model model) {
        return "redirect:/";
    }

    @RequestMapping("/admin/tomodify")
    public String tomodify(User users,int usertype, HttpSession session, Model model) {

        System.out.println(usertype);
        userService.tomodify(users,usertype, session, model);
        UserDTO u = (UserDTO)session.getAttribute("USER_INFO");
        u = userService.getUserById(u.getUserid());
        session.removeAttribute("USER_INFO");
        session.setAttribute("USER_INFO",u);
        return "redirect:/modify";
    }

    @GetMapping("/adminhome")
    public String adminHome() {
        return "competition/adminhome";
    }

    @GetMapping("/admin/create-team")
    public String createTeam() {

        return "team/create-team";
    }

    @GetMapping("/modify")
    public String modify(User users, Model model, HttpSession session) {
        userService.modify(session, model);

        return "user/user-profile";
    }

    @GetMapping("/manage")
    public String manage(int tid, Model model) {
        List<UserDTO> ul = ts.selectStudentsByTeamID(tid);
        TeamDTO dto = ts.selectTeamById(tid);
        model.addAttribute("tn", dto.getTeamname());
        model.addAttribute("tc", dto.getCaptainid());
        model.addAttribute("students", ul);
        System.out.println(ul);
        model.addAttribute("tid", tid);
        UserDTO t = userService.getUserById(dto.getAdviserTeacher());
        model.addAttribute("teacherInfo", t);
        return "/team/management";
    }

    @PostMapping("/modifyteam")
    public String modifyTeam(int tid, String teamName, String teacher, @RequestParam(value = "students[]") List<String> students) {
        ts.updateById(tid, teamName, teacher, students);
        System.out.println("tid:" + tid);
        System.out.println("tn:" + teamName);
        System.out.println("tea:" + teacher);
        System.out.println("stu:" + students);
        return "redirect:/manage?tid=" + tid;
    }
}
